package com.ghr.config;

import lombok.extern.slf4j.Slf4j;
import org.apache.http.HttpHost;
import org.apache.http.auth.AuthScope;
import org.apache.http.auth.UsernamePasswordCredentials;
import org.apache.http.client.CredentialsProvider;
import org.apache.http.impl.client.BasicCredentialsProvider;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestHighLevelClient;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
@Slf4j
public class ElasticSearchConfiguration {

    @Value("${elasticsearch.schema:http}") // 默认值为 http
    private String schema;

    @Value("${elasticsearch.address:localhost:9200}") // 默认值为 localhost:9200
    private String address;

    @Value("${elasticsearch.username:}") // 默认值为空
    private String username;

    @Value("${elasticsearch.password:}") // 默认值为空
    private String password;

    @Value("${elasticsearch.connectTimeout}")
    private int connectTimeout;

    @Value("${elasticsearch.socketTimeout}")
    private int socketTimeout;

    @Bean
    public RestHighLevelClient client() {
        log.info("Creating RestHighLevelClient");
        // 解析地址和端口
        String[] hostAndPort = address.split(":");
        String host = hostAndPort[0];
        int port = Integer.parseInt(hostAndPort[1]);

        // 创建 HttpHost
        HttpHost httpHost = new HttpHost(host, port, schema);

        // 创建 RestHighLevelClient
        return new RestHighLevelClient(
                RestClient.builder(httpHost)
                        .setRequestConfigCallback(requestConfigBuilder -> {
                            // 设置超时时间
                            requestConfigBuilder.setConnectTimeout(connectTimeout); // 连接超时
                            requestConfigBuilder.setSocketTimeout(socketTimeout);  // 套接字超时
                            return requestConfigBuilder;
                        })
                        .setHttpClientConfigCallback(httpClientBuilder -> {
                            // 如果需要认证，添加认证信息
                            if (!username.isEmpty() && !password.isEmpty()) {
                                httpClientBuilder.setDefaultCredentialsProvider(credentialsProvider(username, password));
                            }
                            return httpClientBuilder;
                        })
        );
    }

    // 创建认证信息
    private CredentialsProvider credentialsProvider(String username, String password) {
        CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
        credentialsProvider.setCredentials(
                AuthScope.ANY,
                new UsernamePasswordCredentials(username, password)
        );
        return credentialsProvider;
    }
}
